package gatech.cs2340.adventuretime.server;

import java.io.File;
import java.util.LinkedList;
import com.db4o.*;
import com.db4o.cs.Db4oClientServer;
import java.net.*;
import java.io.*;

/**
 * This is the class the server runs on startup.  It establishes a connection to the db,
 * accepts network connections, and spawns sessions.
 * @author greg
 *
 */
public class Server {
	
	// constants for the database.  The file is "doctors_office" and the port
	// is 0 to denote only local connectivity
	static String DB4OFILENAME = "doctors_office";
	static int PORT = 0;
	
	/**
	 * a list of all currently active sessions
	 */
	LinkedList<Session> activeSessions;
	
	
	public static void main(String [ ] args) throws Exception {
		// TODO launch server gui
		
		ObjectServer db = null;
		ServerSocket serverSocket = null;
		boolean listening = true;

		try {

			db = Db4oClientServer.openServer(Db4oClientServer.newServerConfiguration(), DB4OFILENAME, PORT);
			
			// try / catch for opening a socket
			try {
				serverSocket = new ServerSocket(7777);
			} catch (IOException e) {
	            System.err.println("Could not listen on port: 7777.");
	            System.exit(1);
			}
			
			// listen for clients, accept their connections, and launch a new thread
			while(listening) {
				new ServerThread(serverSocket.accept()).start();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			
		// always want to make sure the connection to the database and the socket are closed
		} finally {
			if(serverSocket != null)
				serverSocket.close();
			
			if(db != null)
				db.close();
		}
	}
}
